package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;


import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{
    private StringRedisTemplate stringRedisTemplate;
    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID()
                                               .toString(true) + "-";
    private String name;
    //提前准备一个lua脚本
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 尝试获取锁
     * @param timeoutSec
     * @return
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        //存入Redis的时候加上线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        //每一个用户一把锁,不同业务不同锁
        Boolean success = stringRedisTemplate.opsForValue().
                setIfAbsent(KEY_PREFIX + name,
                threadId + "", timeoutSec,
                        TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    //使用lua脚本来释放锁-->解决获取线程标识和释放锁之间产生的线程安全问题
    @Override
    public void unlock() {
         //执行lua脚本-->一行代码解决原子性问题
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId());
    }

//    @Override
//    public void unlock() {
//        /**
//         * 释放锁
//         */
//        String threadId = ID_PREFIX + Thread.currentThread().getId();
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
//        /**
//         * 释放锁之前看是不是当前线程的标识
//         */
//        if (threadId.equals(id)) {
//            //只有锁标记相同才去删除
//            stringRedisTemplate.delete(KEY_PREFIX + name);
//        }
//    }
}
